// index.js
const api = require('../../utils/api');
const init = require('../../utils/init');

Page({
  data: {
    dessertList: [],
    searchValue: '',
    loading: true,
    isEmpty: false,
    errorMsg: '',
    navHeight: 0,
    isRefreshing: false,
    lastRefreshTime: 0,
    maxCharsPerLine: 18, // 假设每行最多18个字符
    maxLines: 2
  },

  // 处理文本截断
  truncateText: function(text) {
    const maxLength = this.data.maxCharsPerLine * this.data.maxLines;
    if (text && text.length > maxLength) {
      return text.substring(0, maxLength - 2) + '...';
    }
    return text;
  },

  onNavHeightChange: function(e) {
    const height = e.detail.height;
    // 更新导航栏高度
    this.setData({
      navHeight: height
    });
    // 更新容器样式
    wx.nextTick(function() {
      const query = wx.createSelectorQuery();
      query.select('.container').fields({
        node: true,
        size: true
      }).exec(function(res) {
        if (res[0] && res[0].node) {
          res[0].node.style.paddingTop = height + 'px';
        }
      });
    });
  },

  onLoad: function() {
    // 初始化应用
    init.initApp();
    
    // 加载甜点列表
    this.loadDessertList();
  },
  
  // 加载甜点列表数据
  loadDessertList: function() {
    const self = this;
    const isRefresh = this.data.isRefreshing;
    
    if (!isRefresh) {
      this.setData({ 
        loading: true, 
        isEmpty: false,
        errorMsg: ''
      });
    }
    
    // 记录刷新时间
    const currentTime = Date.now();
    this.setData({
      lastRefreshTime: currentTime
    });
    
    api.getDessertList()
      .then(function(data) {
        // 确保至少显示加载动画500ms
        const loadingTime = Date.now() - self.data.lastRefreshTime;
        const minDelay = Math.max(0, 500 - loadingTime);
        
        setTimeout(function() {
          // 处理每个甜点的配料文本
          const processedData = data.map(function(item) {
            return {
              id: item.id,
              name: item.name,
              ingredients: self.truncateText(item.ingredients),
              instructions: item.instructions,
              image_url: item.image_url
            };
          });
          
          self.setData({
            dessertList: processedData,
            loading: false,
            isEmpty: data.length === 0,
            isRefreshing: false
          });
          
          if (data.length > 0) {
            wx.vibrateShort({ type: 'medium' }); // 轻微振动提示加载完成
          }
        }, minDelay);
      })
      .catch(function(err) {
        console.error('加载甜点列表失败:', err);
        self.setData({
          loading: false,
          isEmpty: true,
          errorMsg: '加载失败，请下拉刷新重试',
          isRefreshing: false
        });
        
        wx.showToast({
          title: '加载失败',
          icon: 'error',
          duration: 2000
        });
      });
  },
  
  // 搜索框输入事件
  onSearchInput: function(e) {
    this.setData({
      searchValue: e.detail.value
    });
  },
  
  // 搜索按钮点击事件
  onSearchConfirm: function() {
    const keyword = this.data.searchValue.trim();
    this.searchDesserts(keyword);
  },
  
  // 清除搜索内容
  onClearSearch: function() {
    this.setData({
      searchValue: ''
    });
    this.loadDessertList();
  },
  
  // 搜索甜点
  searchDesserts: function(keyword) {
    const self = this;
    
    this.setData({ 
      loading: true, 
      isEmpty: false,
      errorMsg: ''
    });
    
    api.searchDesserts(keyword)
      .then(function(data) {
        // 处理每个甜点的配料文本
        const processedData = data.map(function(item) {
          return {
            id: item.id,
            name: item.name,
            ingredients: self.truncateText(item.ingredients),
            instructions: item.instructions,
            image_url: item.image_url
          };
        });
        
        self.setData({
          dessertList: processedData,
          loading: false,
          isEmpty: data.length === 0
        });
      })
      .catch(function(err) {
        console.error('搜索甜点失败:', err);
        self.setData({
          loading: false,
          isEmpty: true,
          errorMsg: '搜索失败，请稍后再试'
        });
        
        wx.showToast({
          title: '搜索失败',
          icon: 'none'
        });
      });
  },
  
  // 点击甜点项，跳转到详情页
  onDessertTap: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + id
    });
  },
  
  // 下拉刷新
  onPullDownRefresh: function() {
    this.setData({
      isRefreshing: true
    });
    
    this.loadDessertList();

    setTimeout(function() {
      wx.stopPullDownRefresh();
    }, 800);
  }
});